package com.FH.util;

import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

/**
 * Token类
 * 验证接口唯一设备登陆
 */
public class Token {

	/**
	 * 生成TOKEN
	 * @param encryptText被签名的字符串 
	 * @param encryptKey密钥 
	 * @return token
	 */
	public static String createToken(String encryptText)
	{
		byte[] bytes;
		String token = "";
		try 
		{
			bytes = HMACSHA1.HmacSHA1Encrypt(encryptText,"FH");
			BASE64Encoder b64encoder = new BASE64Encoder();
	        token = b64encoder.encode(bytes);
	        
		} catch (Exception e) {
			e.getMessage();
		}
		return token;
	}
	
	
	
	/**  
	 *  时间戳+MD5+二进制转16进制
	 * Created on 2012-1-16  
	 * <p>Description:签名方法</p>  
	 */
	public static String signature(String key) throws IOException {
		// 时间戳参数  
		String timekey= String.valueOf(System.currentTimeMillis());
		// 使用MD5对待签名串求签  
		byte[] bytes = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			bytes = md5.digest(timekey.toString().getBytes("UTF-8"));
		} catch (GeneralSecurityException ex) {
			throw new IOException(ex);
		}
		// 将MD5输出的二进制结果转换为小写的十六进制  
		StringBuilder sign = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(bytes[i] & 0xFF);
			if (hex.length() == 1) {
				sign.append("0");
			}
			sign.append(hex);
		}
		return sign.toString();
	}
	
	
	
//	public static void main(String[] args) {
//		System.out.println("1111");
//		try {
//			String dd = signature("15829717091");
//			System.out.println(dd);
//			
//			byte[] bytes = HMACSHA1.HmacSHA1Encrypt("15829717091","FH");
//			BASE64Encoder b64encoder = new BASE64Encoder();
//	        String temp = b64encoder.encode(bytes);
//			System.out.println(temp);
//			
//		} catch (Exception e) {
//			e.getMessage();
//		}
//	}
}
